<template>
  <div class="app-container">
    <el-button-group style="margin-bottom: 16px;">
      <el-button @click="goTo('/content/announcement')">公告管理</el-button>
      <el-button @click="goTo('/content/help')">帮助中心</el-button>
      <el-button @click="goTo('/content/carousel')">轮播图</el-button>
      <el-button @click="goTo('/permission/role')">角色管理</el-button>
    </el-button-group>
    <el-card>
      <template #header>
        <div class="card-header">
          <span>系统基础配置</span>
        </div>
      </template>
      
      <el-tabs v-model="activeTab">
        <!-- 系统参数配置 -->
        <el-tab-pane label="系统参数" name="system">
          <el-form
            ref="systemFormRef"
            :model="systemForm"
            :rules="systemRules"
            label-width="150px"
          >
            <el-collapse v-model="activeCollapse" style="margin-bottom: 20px;">
              <el-collapse-item title="基础信息" name="base">
                <el-form-item label="系统名称" prop="systemName">
                  <el-input v-model="systemForm.systemName" placeholder="请输入系统名称" />
                </el-form-item>
                <el-form-item label="系统Logo" prop="systemLogo">
                  <el-upload
                    class="logo-uploader"
                    action="#"
                    :auto-upload="false"
                    :on-change="handleLogoChange"
                    :show-file-list="false"
                  >
                    <img v-if="systemForm.systemLogo" :src="systemForm.systemLogo" class="logo-image" />
                    <el-icon v-else class="logo-uploader-icon"><Plus /></el-icon>
                  </el-upload>
                  <div class="logo-tip">建议尺寸：200px * 60px，支持JPG、PNG格式</div>
                </el-form-item>
                <el-form-item label="系统描述" prop="systemDesc">
                  <el-input
                    v-model="systemForm.systemDesc"
                    type="textarea"
                    placeholder="请输入系统描述"
                    :rows="3"
                  />
                </el-form-item>
                <el-form-item label="备案号" prop="icp">
                  <el-input v-model="systemForm.icp" placeholder="请输入备案号" />
                </el-form-item>
              </el-collapse-item>
              <el-collapse-item title="联系方式" name="contact">
                <el-form-item label="客服电话" prop="serviceTel">
                  <el-input v-model="systemForm.serviceTel" placeholder="请输入客服电话" />
                </el-form-item>
                <el-form-item label="客服邮箱" prop="serviceEmail">
                  <el-input v-model="systemForm.serviceEmail" placeholder="请输入客服邮箱" />
                </el-form-item>
              </el-collapse-item>
              <el-collapse-item title="其他" name="other">
                <el-form-item label="系统维护模式" prop="maintenance">
                  <el-switch
                    v-model="systemForm.maintenance"
                    :active-value="1"
                    :inactive-value="0"
                  />
                </el-form-item>
                <el-form-item label="维护提示信息" prop="maintenanceMsg" v-if="systemForm.maintenance === 1">
                  <el-input
                    v-model="systemForm.maintenanceMsg"
                    type="textarea"
                    placeholder="请输入维护提示信息"
                    :rows="3"
                  />
                </el-form-item>
              </el-collapse-item>
            </el-collapse>
            <el-form-item>
              <el-button type="primary" @click="saveSystemConfig">保存设置</el-button>
              <el-button @click="resetSystemForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 支付配置 -->
        <el-tab-pane label="支付配置" name="payment">
          <el-form
            ref="paymentFormRef"
            :model="paymentForm"
            :rules="paymentRules"
            label-width="150px"
          >
            <el-divider content-position="left">微信支付配置</el-divider>
            <el-form-item label="启用微信支付" prop="wxpayEnabled">
              <el-switch
                v-model="paymentForm.wxpayEnabled"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
            
            <template v-if="paymentForm.wxpayEnabled === 1">
              <el-form-item label="商户ID" prop="wxpayMchId">
                <el-input v-model="paymentForm.wxpayMchId" placeholder="请输入微信支付商户ID" />
              </el-form-item>
              
              <el-form-item label="商户密钥" prop="wxpayKey">
                <el-input v-model="paymentForm.wxpayKey" placeholder="请输入微信支付商户密钥" show-password />
              </el-form-item>
              
              <el-form-item label="AppID" prop="wxpayAppId">
                <el-input v-model="paymentForm.wxpayAppId" placeholder="请输入微信支付AppID" />
              </el-form-item>
              
              <el-form-item label="商户证书" prop="wxpayCert">
                <el-upload
                  class="cert-uploader"
                  action="#"
                  :auto-upload="false"
                  :on-change="handleWxpayCertChange"
                  :show-file-list="true"
                  :file-list="wxpayCertFiles"
                >
                  <el-button type="primary">上传证书</el-button>
                  <div class="cert-tip">支持.p12格式</div>
                </el-upload>
              </el-form-item>
            </template>
            
            <el-divider content-position="left">支付宝配置</el-divider>
            <el-form-item label="启用支付宝" prop="alipayEnabled">
              <el-switch
                v-model="paymentForm.alipayEnabled"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
            
            <template v-if="paymentForm.alipayEnabled === 1">
              <el-form-item label="应用ID" prop="alipayAppId">
                <el-input v-model="paymentForm.alipayAppId" placeholder="请输入支付宝应用ID" />
              </el-form-item>
              
              <el-form-item label="商户私钥" prop="alipayPrivateKey">
                <el-input 
                  v-model="paymentForm.alipayPrivateKey" 
                  type="textarea"
                  placeholder="请输入支付宝商户私钥" 
                  :rows="3"
                  show-password
                />
              </el-form-item>
              
              <el-form-item label="支付宝公钥" prop="alipayPublicKey">
                <el-input 
                  v-model="paymentForm.alipayPublicKey" 
                  type="textarea"
                  placeholder="请输入支付宝公钥" 
                  :rows="3"
                />
              </el-form-item>
            </template>
            
            <el-form-item>
              <el-button type="primary" @click="savePaymentConfig">保存设置</el-button>
              <el-button @click="resetPaymentForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 短信配置 -->
        <el-tab-pane label="短信配置" name="sms">
          <el-form
            ref="smsFormRef"
            :model="smsForm"
            :rules="smsRules"
            label-width="150px"
          >
            <el-form-item label="短信服务商" prop="smsProvider">
              <el-select v-model="smsForm.smsProvider" placeholder="请选择短信服务商">
                <el-option label="阿里云" value="aliyun" />
                <el-option label="腾讯云" value="tencent" />
              </el-select>
            </el-form-item>
            
            <template v-if="smsForm.smsProvider === 'aliyun'">
              <el-form-item label="AccessKey ID" prop="aliyunAccessKeyId">
                <el-input v-model="smsForm.aliyunAccessKeyId" placeholder="请输入阿里云AccessKey ID" />
              </el-form-item>
              
              <el-form-item label="AccessKey Secret" prop="aliyunAccessKeySecret">
                <el-input v-model="smsForm.aliyunAccessKeySecret" placeholder="请输入阿里云AccessKey Secret" show-password />
              </el-form-item>
              
              <el-form-item label="短信签名" prop="aliyunSignName">
                <el-input v-model="smsForm.aliyunSignName" placeholder="请输入短信签名" />
              </el-form-item>
            </template>
            
            <template v-if="smsForm.smsProvider === 'tencent'">
              <el-form-item label="SecretId" prop="tencentSecretId">
                <el-input v-model="smsForm.tencentSecretId" placeholder="请输入腾讯云SecretId" />
              </el-form-item>
              
              <el-form-item label="SecretKey" prop="tencentSecretKey">
                <el-input v-model="smsForm.tencentSecretKey" placeholder="请输入腾讯云SecretKey" show-password />
              </el-form-item>
              
              <el-form-item label="应用SDKAppID" prop="tencentSdkAppId">
                <el-input v-model="smsForm.tencentSdkAppId" placeholder="请输入腾讯云应用SDKAppID" />
              </el-form-item>
              
              <el-form-item label="短信签名" prop="tencentSignName">
                <el-input v-model="smsForm.tencentSignName" placeholder="请输入短信签名" />
              </el-form-item>
            </template>
            
            <el-divider content-position="left">短信模板配置</el-divider>
            
            <el-form-item label="验证码短信模板ID" prop="verifyCodeTemplateId">
              <el-input v-model="smsForm.verifyCodeTemplateId" placeholder="请输入验证码短信模板ID" />
            </el-form-item>
            
            <el-form-item label="通知短信模板ID" prop="notificationTemplateId">
              <el-input v-model="smsForm.notificationTemplateId" placeholder="请输入通知短信模板ID" />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="saveSmsConfig">保存设置</el-button>
              <el-button @click="resetSmsForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 邮件配置 -->
        <el-tab-pane label="邮件配置" name="email">
          <el-form
            ref="emailFormRef"
            :model="emailForm"
            :rules="emailRules"
            label-width="150px"
          >
            <el-form-item label="SMTP服务器" prop="smtpServer">
              <el-input v-model="emailForm.smtpServer" placeholder="请输入SMTP服务器地址" />
            </el-form-item>
            
            <el-form-item label="SMTP端口" prop="smtpPort">
              <el-input v-model.number="emailForm.smtpPort" placeholder="请输入SMTP端口" />
            </el-form-item>
            
            <el-form-item label="发件人邮箱" prop="senderEmail">
              <el-input v-model="emailForm.senderEmail" placeholder="请输入发件人邮箱" />
            </el-form-item>
            
            <el-form-item label="发件人名称" prop="senderName">
              <el-input v-model="emailForm.senderName" placeholder="请输入发件人名称" />
            </el-form-item>
            
            <el-form-item label="邮箱密码/授权码" prop="emailPassword">
              <el-input v-model="emailForm.emailPassword" placeholder="请输入邮箱密码或授权码" show-password />
            </el-form-item>
            
            <el-form-item label="启用SSL" prop="enableSsl">
              <el-switch
                v-model="emailForm.enableSsl"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
            
            <el-divider content-position="left">测试邮件</el-divider>
            
            <el-form-item label="测试收件人" prop="testRecipient">
              <el-input v-model="emailForm.testRecipient" placeholder="请输入测试收件人邮箱" />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="saveEmailConfig">保存设置</el-button>
              <el-button type="success" @click="testEmailConfig">发送测试邮件</el-button>
              <el-button @click="resetEmailForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, UploadFile, UploadUserFile } from 'element-plus'
import { post } from '@/utils/request'
import { useRouter } from 'vue-router'

// 当前激活的选项卡
const activeTab = ref('system')

// 系统参数表单
const systemFormRef = ref<FormInstance | null>(null)
const systemForm = reactive({
  systemName: 'AI助农管理系统',
  systemLogo: '',
  systemDesc: '基于人工智能的农产品销售平台管理系统',
  icp: '京ICP备12345678号',
  serviceTel: '400-123-4567',
  serviceEmail: 'service@example.com',
  maintenance: 0,
  maintenanceMsg: '系统正在维护中，请稍后再试'
})

// 系统参数验证规则
const activeCollapse = ref(['base', 'contact'])
const systemRules = {
  systemName: [{ required: true, message: '请输入系统名称', trigger: 'blur' }],
  serviceEmail: [
    { required: true, message: '请输入客服邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  serviceTel: [
    { required: true, message: '请输入客服电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$|^400-\d{3}-\d{4}$/, message: '请输入正确的手机号或400电话', trigger: 'blur' }
  ]
}

// 支付配置表单
const paymentFormRef = ref<FormInstance | null>(null)
const paymentForm = reactive({
  wxpayEnabled: 0,
  wxpayMchId: '',
  wxpayKey: '',
  wxpayAppId: '',
  wxpayCert: '',
  alipayEnabled: 0,
  alipayAppId: '',
  alipayPrivateKey: '',
  alipayPublicKey: ''
})

// 支付配置验证规则
const paymentRules = {
  wxpayMchId: [{ required: true, message: '请输入微信支付商户ID', trigger: 'blur' }],
  wxpayKey: [{ required: true, message: '请输入微信支付商户密钥', trigger: 'blur' }],
  wxpayAppId: [{ required: true, message: '请输入微信支付AppID', trigger: 'blur' }],
  alipayAppId: [{ required: true, message: '请输入支付宝应用ID', trigger: 'blur' }],
  alipayPrivateKey: [{ required: true, message: '请输入支付宝商户私钥', trigger: 'blur' }],
  alipayPublicKey: [{ required: true, message: '请输入支付宝公钥', trigger: 'blur' }]
}

// 微信支付证书文件列表
const wxpayCertFiles = ref<UploadUserFile[]>([])

// 短信配置表单
const smsFormRef = ref<FormInstance | null>(null)
const smsForm = reactive({
  smsProvider: 'aliyun',
  aliyunAccessKeyId: '',
  aliyunAccessKeySecret: '',
  aliyunSignName: '',
  tencentSecretId: '',
  tencentSecretKey: '',
  tencentSdkAppId: '',
  tencentSignName: '',
  verifyCodeTemplateId: '',
  notificationTemplateId: ''
})

// 短信配置验证规则
const smsRules = {
  smsProvider: [{ required: true, message: '请选择短信服务商', trigger: 'change' }],
  aliyunAccessKeyId: [{ required: true, message: '请输入阿里云AccessKey ID', trigger: 'blur' }],
  aliyunAccessKeySecret: [{ required: true, message: '请输入阿里云AccessKey Secret', trigger: 'blur' }],
  aliyunSignName: [{ required: true, message: '请输入短信签名', trigger: 'blur' }],
  tencentSecretId: [{ required: true, message: '请输入腾讯云SecretId', trigger: 'blur' }],
  tencentSecretKey: [{ required: true, message: '请输入腾讯云SecretKey', trigger: 'blur' }],
  tencentSdkAppId: [{ required: true, message: '请输入腾讯云应用SDKAppID', trigger: 'blur' }],
  tencentSignName: [{ required: true, message: '请输入短信签名', trigger: 'blur' }],
  verifyCodeTemplateId: [{ required: true, message: '请输入验证码短信模板ID', trigger: 'blur' }],
  notificationTemplateId: [{ required: true, message: '请输入通知短信模板ID', trigger: 'blur' }]
}

// 邮件配置表单
const emailFormRef = ref<FormInstance | null>(null)
const emailForm = reactive({
  smtpServer: 'smtp.example.com',
  smtpPort: 465,
  senderEmail: 'sender@example.com',
  senderName: 'AI助农系统',
  emailPassword: '',
  enableSsl: 1,
  testRecipient: ''
})

// 邮件配置验证规则
const emailRules = {
  smtpServer: [{ required: true, message: '请输入SMTP服务器地址', trigger: 'blur' }],
  smtpPort: [
    { required: true, message: '请输入SMTP端口', trigger: 'blur' },
    { type: 'number', message: '端口必须为数字', trigger: 'blur' }
  ],
  senderEmail: [
    { required: true, message: '请输入发件人邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  senderName: [{ required: true, message: '请输入发件人名称', trigger: 'blur' }],
  emailPassword: [{ required: true, message: '请输入邮箱密码或授权码', trigger: 'blur' }],
  testRecipient: [
    { required: true, message: '请输入测试收件人邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 加载配置数据
const loadConfigData = async () => {
  try {
    // 这里应该从API获取配置数据，此处使用模拟数据
    // 实际项目中替换为真实API调用
    // const res = await get('/api/system/config')
    
    // 模拟加载数据
    // ...实际项目中应该使用API返回的数据更新表单
  } catch (error) {
    console.error('加载配置数据失败:', error)
    ElMessage.error('加载配置数据失败')
  }
}

// 处理Logo变更
const handleLogoChange = (file: UploadFile) => {
  // 检查文件类型
  if (!file.raw) {
    ElMessage.error('上传文件不能为空!')
    return
  }
  
  const isJPG = file.raw.type === 'image/jpeg'
  const isPNG = file.raw.type === 'image/png'
  
  if (!isJPG && !isPNG) {
    ElMessage.error('Logo图片只能是JPG或PNG格式!')
    return
  }
  
  // 检查文件大小
  const isLt2M = file.size && file.size / 1024 / 1024 < 2
  
  if (!isLt2M) {
    ElMessage.error('Logo图片大小不能超过2MB!')
    return
  }
  
  // 预览图片
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = () => {
    systemForm.systemLogo = reader.result as string
  }
}

// 处理微信支付证书变更
const handleWxpayCertChange = (file: UploadFile) => {
  // 检查文件类型
  if (!file.raw) {
    ElMessage.error('上传文件不能为空!')
    return
  }
  
  const isP12 = file.raw.name.endsWith('.p12')
  
  if (!isP12) {
    ElMessage.error('商户证书必须是.p12格式!')
    return
  }
  
  wxpayCertFiles.value = [file]
  paymentForm.wxpayCert = file.raw.name
}

// 保存系统配置
const saveSystemConfig = async () => {
  await post('/api/system/config', systemForm)
  ElMessage.success('保存成功')
}

// 重置系统表单
const resetSystemForm = () => {
  if (!systemFormRef.value) return
  systemFormRef.value.resetFields()
}

// 保存支付配置
const savePaymentConfig = async () => {
  await post('/api/system/payment', paymentForm)
  ElMessage.success('保存成功')
}

// 重置支付表单
const resetPaymentForm = () => {
  if (!paymentFormRef.value) return
  paymentFormRef.value.resetFields()
  wxpayCertFiles.value = []
}

// 保存短信配置
const saveSmsConfig = async () => {
  await post('/api/system/sms', smsForm)
  ElMessage.success('保存成功')
}

// 重置短信表单
const resetSmsForm = () => {
  if (!smsFormRef.value) return
  smsFormRef.value.resetFields()
}

// 保存邮件配置
const saveEmailConfig = async () => {
  if (!emailFormRef.value) return
  
  try {
    await emailFormRef.value.validate()
    
    // 这里应该调用API保存配置
    // 实际项目中替换为真实API调用
    // await post('/api/system/config/email', emailForm)
    
    // 模拟保存成功
    ElMessage.success('邮件配置保存成功')
  } catch (error) {
    console.error('保存邮件配置失败:', error)
    ElMessage.error('保存邮件配置失败')
  }
}

// 测试邮件配置
const testEmailConfig = async () => {
  if (!emailFormRef.value) return
  
  try {
    // 验证测试收件人
    await emailFormRef.value.validateField('testRecipient')
    
    // 这里应该调用API发送测试邮件
    // 实际项目中替换为真实API调用
    // await post('/api/system/config/email/test', { recipient: emailForm.testRecipient })
    
    // 模拟发送成功
    ElMessage.success('测试邮件发送成功，请查收')
  } catch (error) {
    console.error('发送测试邮件失败:', error)
    ElMessage.error('发送测试邮件失败')
  }
}

// 重置邮件表单
const resetEmailForm = () => {
  if (!emailFormRef.value) return
  emailFormRef.value.resetFields()
}

// 组件挂载时加载配置数据
onMounted(() => {
  loadConfigData()
})

const router = useRouter()
const goTo = (path: string) => router.push(path)
const goToBasic = () => {
  router.push('/system/basic')
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo-uploader {
  .logo-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 60px;
    line-height: 60px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
  }
  
  .logo-image {
    width: 200px;
    height: 60px;
    display: block;
  }
}

.logo-tip, .cert-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

:deep(.el-upload-list) {
  width: 360px;
}
</style> 